import datetime
import random
from flask import render_template
from flask_mail import Message
from common.mail import mail
from common.database import db
from model.user import User
from model.verify import Verify
from result.result import Result
from result.result_code import ResultCode
from utils.check_data import check_data
from config.mail_config import MAIL_USERNAME
from utils.to_md5 import to_md5


class EmailService(object):

    @staticmethod
    def register(data):
        if not check_data(data, ["email"]):
            return Result.error(ResultCode.DATA_ERROR.value, "必填项不可为空")
        email = data['email']
        users = User.query.filter_by(email=email).all()
        if len(users) > 0:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, "此邮箱已经注册，无法再次注册")
        # ip_address = get_server_ip()
        # print(ip_address)
        # if ip_address is None:
        #     ip_address = 'localhost'
        # code = random.randint(100000, 999999)
        # title = "用户注册"
        # h1 = "邮箱验证"
        h2 = f"您正在使用:{email} 注册飞机表面缺陷管理系统账户,请妥善保管您的验证码，打死都不要告诉别人。"
        return EmailService.send_code_email(email, h2)
        # h3 = f"验证码有限期5分钟，如非本人操作，请忽略此邮件。"
        # code_text = str(code)
        # val_time = datetime.datetime.now() + datetime.timedelta(minutes=5)
        # try:
        #     verify_list = Verify.query.filter_by(email=email).all()
        #     if len(verify_list):
        #         verify_list[0].code = code
        #         verify_list[0].val_time = val_time
        #         db.session.commit()
        #     else:
        #         verify = Verify(email=email, code=code, val_time=val_time)
        #         db.session.add(verify)
        #         db.session.commit()
        # except Exception as e:
        #     print('数据库错误')
        #     print(e)
        #     return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "SERVER ERROR")
        # # 发送邮箱
        # try:
        #     msg = Message("飞机表面缺陷检测系统", sender=MAIL_USERNAME, recipients=[email])
        #     msg.html = render_template('email_check.html', h1=h1, h2=h2, h3=h3, code=code)
        #     mail.send(msg)
        # except Exception as e:
        #     print('邮箱发送失败')
        #     print(e)
        #     return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "SERVER ERROR, send email error")
        # return Result.success()

    @staticmethod
    def findPsd(data):
        email = data['email']
        user = User.query.filter_by(email=email).first()
        if user is None:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, "邮箱没有注册")
        h2 = f"您正在修改飞机表面缺陷管理系统账户密码,请妥善保管您的验证码，打死都不要告诉别人。"
        return EmailService.send_code_email(email, h2)

    # @staticmethod
    # def check(code):
    #     verify = Verify.query.filter_by(code=code).first()
    #     if datetime.datetime.now() > verify.val_time:
    #         return render_template('email_check.html', h1='验证码已经过期！')
    #     elif verify.status == 1:
    #         return render_template('email_check.html', h1='此链接已经使用过啦！')
    #     else:
    #         verify.status = 1
    #         db.session.commit()
    #         return render_template('email_check.html', h1='邮箱验证成功,您的账号已经注册成功，请使用邮箱+密码登录系统')

    @staticmethod
    def send_code_email(email, h2):
        h1 = "邮箱验证"
        h3 = f"验证码有限期5分钟，如非本人操作，请忽略此邮件。"
        code = random.randint(100000, 999999)
        val_time = datetime.datetime.now() + datetime.timedelta(minutes=5)
        try:
            verify_list = Verify.query.filter_by(email=email).all()
            if len(verify_list):
                verify_list[0].code = to_md5(str(code))
                verify_list[0].val_time = val_time
                db.session.commit()
            else:
                verify = Verify(email=email, code=to_md5(str(code)), val_time=val_time)
                db.session.add(verify)
                db.session.commit()
        except Exception as e:
            print('数据库错误')
            print(e)
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "SERVER ERROR")
        # 发送邮箱
        try:
            msg = Message("飞机表面缺陷检测系统", sender=MAIL_USERNAME, recipients=[email])
            msg.html = render_template('email_check.html', h1=h1, h2=h2, h3=h3, code=code)
            mail.send(msg)
        except Exception as e:
            print('邮箱发送失败')
            print(e)
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "SERVER ERROR, send email error")
        return Result.success()
